package com.lyy.component;

import cn.hutool.core.util.StrUtil;
import com.lyy.annotation.Token;
import com.lyy.JwtUtil;
import org.springframework.stereotype.Component;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Liangyaoyun
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handle) throws Exception {
        //如果请求不指向控制方法，则直接放行
        if (!(handle instanceof HandlerMethod)) {
            return true;
        }
        //判断方法上是否存在注解@Token注解
        HandlerMethod handlerMethod = (HandlerMethod) handle;
        Method method = handlerMethod.getMethod();
        if (!method.isAnnotationPresent(Token.class)) {
            return true;
        }



        //从请求头中获取token
        String token = request.getHeader("token");

        //判断token是否正确
        Map<String, Object> resultMap = JwtUtil.verify(token);

        //查看当前token是否过期,若是则返回过期提示
        if ((boolean) resultMap.get("expireSoon")) {
            Map<String, Object> responseMap = new HashMap<>(3);
            responseMap.put("code", 201);
            responseMap.put("message", "token即将在30分钟内过期，请及时更换");
            responseMap.put("data", responseMap.get("newToken"));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(responseMap) ;
            return false;
        }
        if (StrUtil.isBlank(token)) {
            throw new RuntimeException("请求头中未携带token");
        }


        Integer userId = (Integer) resultMap.get("userId");
        //将用户的主题存在服务端的会话中
        request.getSession().setAttribute("userId", userId);
        return true;

    }

}
